package com.example.guess;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Random;

/**
 * 猜数字游戏 - 使用Java Swing实现
 * 游戏规则：系统随机生成1-100之间的数字，玩家猜测并获得提示
 */
public class GuessNumberGame extends JFrame implements ActionListener {
    // 游戏组件
    private JTextField inputField;           // 输入框
    private JButton guessButton;            // 猜测按钮
    private JButton resetButton;            // 重新开始按钮
    private JLabel titleLabel;              // 标题标签
    private JLabel promptLabel;             // 提示标签
    private JLabel resultLabel;             // 结果标签
    private JLabel attemptsLabel;           // 尝试次数标签
    private JTextArea historyArea;          // 历史记录区域
    private JScrollPane scrollPane;         // 滚动面板
    
    // 游戏状态变量
    private int targetNumber;               // 目标数字
    private int attempts;                   // 尝试次数
    private Random random;                  // 随机数生成器
    private boolean gameOver;               // 游戏结束标志
    
    /**
     * 构造函数 - 初始化游戏界面和组件
     */
    public GuessNumberGame() {
        random = new Random();
        initializeComponents();
        setupLayout();
        setupEventListeners();
        startNewGame();
        
        // 窗口设置
        setTitle("猜数字游戏");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);
        pack();
        setLocationRelativeTo(null); // 居中显示
        setVisible(true);
    }
    
    /**
     * 初始化所有GUI组件
     */
    private void initializeComponents() {
        // 创建标签组件
        titleLabel = new JLabel("🎯 猜数字游戏", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 24));
        titleLabel.setForeground(new Color(51, 102, 153));
        
        promptLabel = new JLabel("请输入1-100之间的数字：", JLabel.CENTER);
        promptLabel.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        
        resultLabel = new JLabel("开始游戏吧！祝你好运 🍀", JLabel.CENTER);
        resultLabel.setFont(new Font("微软雅黑", Font.BOLD, 16));
        resultLabel.setForeground(new Color(0, 128, 0));
        
        attemptsLabel = new JLabel("尝试次数: 0", JLabel.CENTER);
        attemptsLabel.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        attemptsLabel.setForeground(new Color(102, 102, 102));
        
        // 创建输入组件
        inputField = new JTextField(10);
        inputField.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        inputField.setHorizontalAlignment(JTextField.CENTER);
        
        // 创建按钮组件
        guessButton = new JButton("猜测");
        guessButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        guessButton.setBackground(new Color(51, 153, 255));
        guessButton.setForeground(Color.WHITE);
        guessButton.setFocusPainted(false);
        guessButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        resetButton = new JButton("重新开始");
        resetButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        resetButton.setBackground(new Color(255, 102, 51));
        resetButton.setForeground(Color.WHITE);
        resetButton.setFocusPainted(false);
        resetButton.setCursor(new Cursor(Cursor.HAND_CURSOR));
        
        // 创建历史记录区域
        historyArea = new JTextArea(8, 25);
        historyArea.setFont(new Font("微软雅黑", Font.PLAIN, 12));
        historyArea.setEditable(false);
        historyArea.setBackground(new Color(248, 248, 248));
        historyArea.setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
        
        scrollPane = new JScrollPane(historyArea);
        scrollPane.setBorder(BorderFactory.createTitledBorder("游戏记录"));
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
    }
    
    /**
     * 设置界面布局
     */
    private void setupLayout() {
        setLayout(new BorderLayout(10, 10));
        
        // 顶部面板 - 标题
        JPanel topPanel = new JPanel();
        topPanel.add(titleLabel);
        topPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 5, 10));
        
        // 中心面板 - 游戏区域
        JPanel centerPanel = new JPanel(new BorderLayout(5, 5));
        
        // 游戏信息面板
        JPanel gameInfoPanel = new JPanel(new GridLayout(3, 1, 5, 5));
        gameInfoPanel.add(promptLabel);
        gameInfoPanel.add(resultLabel);
        gameInfoPanel.add(attemptsLabel);
        gameInfoPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        
        // 输入面板
        JPanel inputPanel = new JPanel(new FlowLayout());
        inputPanel.add(inputField);
        inputPanel.add(guessButton);
        inputPanel.add(resetButton);
        inputPanel.setBorder(BorderFactory.createEmptyBorder(5, 10, 5, 10));
        
        centerPanel.add(gameInfoPanel, BorderLayout.NORTH);
        centerPanel.add(inputPanel, BorderLayout.CENTER);
        centerPanel.add(scrollPane, BorderLayout.SOUTH);
        
        // 添加到主窗口
        add(topPanel, BorderLayout.NORTH);
        add(centerPanel, BorderLayout.CENTER);
        
        // 设置边框
        getRootPane().setBorder(BorderFactory.createEmptyBorder(5, 5, 5, 5));
    }
    
    /**
     * 设置事件监听器
     */
    private void setupEventListeners() {
        guessButton.addActionListener(this);
        resetButton.addActionListener(this);
        
        // 输入框回车事件
        inputField.addActionListener(this);
        
        // 输入框焦点事件
        inputField.addFocusListener(new java.awt.event.FocusAdapter() {
            public void focusGained(java.awt.event.FocusEvent evt) {
                inputField.selectAll();
            }
        });
    }
    
    /**
     * 开始新游戏
     */
    private void startNewGame() {
        targetNumber = random.nextInt(100) + 1; // 生成1-100的随机数
        attempts = 0;
        gameOver = false;
        
        // 重置界面
        inputField.setText("");
        inputField.setEnabled(true);
        guessButton.setEnabled(true);
        resultLabel.setText("开始游戏吧！祝你好运 🍀");
        resultLabel.setForeground(new Color(0, 128, 0));
        attemptsLabel.setText("尝试次数: 0");
        historyArea.append("🎮 新游戏开始！目标数字已生成（1-100）\n");
        historyArea.append("═══════════════════════════════════════\n");
        
        // 自动滚动到底部
        historyArea.setCaretPosition(historyArea.getDocument().getLength());
        
        // 输入框获得焦点
        inputField.requestFocus();
    }
    
    /**
     * 处理猜测逻辑
     */
    private void processGuess() {
        if (gameOver) return;
        
        try {
            String input = inputField.getText().trim();
            if (input.isEmpty()) {
                showMessage("请输入一个数字！", Color.RED);
                return;
            }
            
            int guess = Integer.parseInt(input);
            
            // 验证输入范围
            if (guess < 1 || guess > 100) {
                showMessage("请输入1-100之间的数字！", Color.RED);
                inputField.selectAll();
                return;
            }
            
            attempts++;
            attemptsLabel.setText("尝试次数: " + attempts);
            
            // 添加到历史记录
            historyArea.append(String.format("第%d次猜测: %d ", attempts, guess));
            
            // 判断猜测结果
            if (guess == targetNumber) {
                // 猜对了
                gameOver = true;
                String message = String.format("🎉 恭喜你！猜对了！答案是 %d", targetNumber);
                showMessage(message, new Color(0, 128, 0));
                
                historyArea.append("✅ 正确！\n");
                historyArea.append(String.format("🏆 游戏结束！共用了 %d 次猜测\n", attempts));
                
                // 评价表现
                String performance = getPerformanceMessage(attempts);
                historyArea.append(performance + "\n");
                historyArea.append("═══════════════════════════════════════\n");
                
                inputField.setEnabled(false);
                guessButton.setEnabled(false);
                
            } else if (guess < targetNumber) {
                // 太小了
                showMessage("📈 太小了！请试试更大的数字", new Color(255, 140, 0));
                historyArea.append("📈 太小了\n");
                
            } else {
                // 太大了
                showMessage("📉 太大了！请试试更小的数字", new Color(255, 140, 0));
                historyArea.append("📉 太大了\n");
            }
            
            // 清空输入框并获得焦点
            inputField.setText("");
            inputField.requestFocus();
            
            // 自动滚动到底部
            historyArea.setCaretPosition(historyArea.getDocument().getLength());
            
        } catch (NumberFormatException e) {
            showMessage("请输入有效的数字！", Color.RED);
            inputField.selectAll();
        }
    }
    
    /**
     * 显示消息
     */
    private void showMessage(String message, Color color) {
        resultLabel.setText(message);
        resultLabel.setForeground(color);
    }
    
    /**
     * 根据尝试次数给出表现评价
     */
    private String getPerformanceMessage(int attempts) {
        if (attempts <= 3) {
            return "🌟 太厉害了！你是猜数字天才！";
        } else if (attempts <= 6) {
            return "👍 很不错！你的直觉很准确！";
        } else if (attempts <= 10) {
            return "😊 不错的表现！继续保持！";
        } else {
            return "💪 虽然用了较多次数，但坚持就是胜利！";
        }
    }
    
    /**
     * 事件处理方法
     */
    @Override
    public void actionPerformed(ActionEvent e) {
        Object source = e.getSource();
        
        if (source == guessButton || source == inputField) {
            processGuess();
        } else if (source == resetButton) {
            int choice = JOptionPane.showConfirmDialog(
                this,
                "确定要重新开始游戏吗？",
                "重新开始",
                JOptionPane.YES_NO_OPTION,
                JOptionPane.QUESTION_MESSAGE
            );
            
            if (choice == JOptionPane.YES_OPTION) {
                startNewGame();
            }
        }
    }
    
    /**
     * 主方法 - 程序入口
     */
    public static void main(String[] args) {
        // 在事件调度线程中创建和显示GUI
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                new GuessNumberGame();
            }
        });
    }
} 